package com.truongnha.clienttn.presentation;

import java.net.HttpURLConnection;
import java.net.URL;

import config.Url;

import android.content.Context;
//import android.net.ConnectivityManager;
//import android.net.NetworkInfo;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class CheckNetwork {
	static private Context context;
	static private boolean isChecked = false;
	static private boolean isAvailable_ = false;

	public CheckNetwork(Context context) {
		super();
		this.context = context;
	}

	static public boolean isAvailable(boolean isCheckAgain) {
		if (isCheckAgain) {
			isChecked = true;
			isAvailable_ = isNetworkAvailable();
		}
		return isAvailable();
	}

	static public boolean isAvailable() {
		if (!isChecked) {
			isChecked = true;
			isAvailable_ = isNetworkAvailable();
		}
		return isAvailable_;
	}

	private static boolean isNetworkAvailable() {
		ConnectivityManager connMgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		if (networkInfo != null && networkInfo.isConnected()) {
			return true;
		} else {
			return false;
		}
	}// end isNetworkAvailable

	static private boolean isNetworkAvailable1() {
		// Log.d("log checking network", "checking");
		// String url = Url.getURLLogin();
		// String csrfmiddlewaretoken = new JSONParser().getCsrfFromUrl(url);
		// if (csrfmiddlewaretoken == null)
		// return false;
		// else
		// return true;
		return CheckReponse.isResponse();
	}

}

class CheckReponse {
	private static String urlString = Url.getURLLogin();

	public static boolean isResponse() {
		try {
			URL url = new URL(urlString);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(1500 /* milliseconds */);
			conn.setConnectTimeout(3000 /* milliseconds */);
			conn.setRequestMethod("GET");
			conn.setDoInput(true);
			// Starts the query
			conn.connect();
			int response = conn.getResponseCode();
			if (response == 200)
				return true;
		} catch (Exception e) {
		}
		return false;
	}
}